﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using NetCoreCMS.Web.Areas.WebApi.Models;

namespace NetCoreCMS.Web.Areas.WebApi.Controllers
{
    /// <summary>
    /// 登录
    /// </summary>
    public class User_LoginController : BaseController
    {
        protected Userconfig userConfig;
        protected Sysconfig sysConfig;
        public IUser_login_logService _user_login_log { get; set; }
        public IUser_point_logService _user_point_log { get; set; }
        [AllowAnonymous]
        [HttpGet]
        public IActionResult Get(string username, string password)
        {
            userConfig = Common.XMLConfig.Userconfig.loadConfig(_env.ContentRootPath);
            sysConfig = Common.XMLConfig.Sysconfig.loadConfig(_env.ContentRootPath);
            //检查用户名密码
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return Ok(new { status=0, msg = "温馨提示：请输入用户名或密码！" });
            }

            Users model = _users.GetModel(username, password, userConfig.emaillogin, userConfig.mobilelogin, true);
            if (model == null)
            {
                return Ok(new { status = 0, msg = "温馨提示：用户名或密码错误，请重试！" });
            }
            //检查用户每天登录是否获得积分
            if (!_user_login_log.ExistsDay(model.user_name) && userConfig.pointloginnum > 0)
            {
                _user_point_log.Add(model.id, model.user_name, userConfig.pointloginnum, "每天登录获得积分", true); //增加用户登录积分
                model = _users.GetModel(username, password, userConfig.emaillogin, userConfig.mobilelogin, true); //更新一下用户信息
            }
            //写入登录日志
            _user_login_log.Add(model.id, model.user_name, "会员登录", CMSRequest.GetClientUserIp(HttpContext));
            #region jwt
            var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                    new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddDays(30)).ToUnixTimeSeconds()}"),
                    new Claim(ClaimTypes.Name, username)
                };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: Const.Domain,
                audience: Const.Domain,
                claims: claims,
                expires: DateTime.Now.AddDays(30),
                signingCredentials: creds);

            return Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                avatarUrl  = sysConfig.weburl+model.avatar,
                nickName=model.user_name,
                status = 1
            });
            #endregion
        }
    }
}